﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.Web.Routing;

namespace ThietBiSo.Helpers
{
    public class MvcSpHandleErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            var controller = filterContext.RouteData.GetRequiredString("controller");
            var action = filterContext.RouteData.GetRequiredString("action");

            filterContext.Controller.TempData["Exception"] = new HandleErrorInfo(filterContext.Exception, controller, action);
            filterContext.ExceptionHandled = true;
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "area", string.Empty },
                { "controller", "Home" },
                { "action", "Error" },
            });
        }
    }

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ButtonClickAttribute : ActionNameSelectorAttribute
    {
        public string Name { get; set; }

        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            return controllerContext.HttpContext.Request[Name] != null;
        }
    }

    public class RoutedAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            //redirect to root LogOn 
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary
                                        {
                                                { "controller", "Account" },
                                                { "action", "LogOn" },
                                                { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
                                        });


            }
        }
    }


}